//
//  JFLoginViewController.m
//  JobFree2.0
//
//  Created by Dale on 2017/6/7.
//  Copyright © 2017年 Dale. All rights reserved.
//

#import "JFLoginViewController.h"
#import "WXApiManager.h"
#import "WXApiRequestHandler.h"
#import "WXApi.h"
#import "AppDelegate.h"
#import "HYBCommonKit.h"
#import "AFNetworking.h"
#import "MMDrawerController.h"
#import "Constant.h"

@interface JFLoginViewController ()<WXApiManagerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *bgImageV;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;

@end

@implementation JFLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (isIPhone4) {
        self.bottomConstraint.constant = 40;
        self.bgImageV.image = [UIImage imageNamed:@"loginBG35"];
    } else if (isIPhone5) {
        self.bottomConstraint.constant = 50;
        self.bgImageV.image = [UIImage imageNamed:@"loginBG40"];
    } else if (isIPhone6) {
        self.bottomConstraint.constant = 60;
        self.bgImageV.image = [UIImage imageNamed:@"loginBG47"];
    } else if (isIPhone6P) {
        self.bottomConstraint.constant = 70;
        self.bgImageV.image = [UIImage imageNamed:@"loginBG55"];
    }
    [WXApiManager sharedManager].delegate = self;
         NSString *accessToken = UserDefaultsGet(WX_ACCESS_TOKEN);
    NSString *openID = UserDefaultsGet(WX_OPEN_ID);
    if (accessToken && openID) {
        [self getAccessToken:accessToken OpenId:openID];
    }
    
}
- (IBAction)handleLoginBtnAction:(UIButton *)sender {
    //微信跳转
    if ([WXApi isWXAppInstalled]) {
        NSString *accessToken = UserDefaultsGet(WX_ACCESS_TOKEN);
        NSString *openID = UserDefaultsGet(WX_OPEN_ID);
        NSString *refreshToken = UserDefaultsGet(WX_REFRESH_TOKEN);
        // 如果已经请求过微信授权登录，那么考虑用已经得到的access_token
        if (accessToken && openID) {
            [super showHudWithText:@"正在登录..."];
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", @"text/plain", nil];
            NSString *refreshUrlStr = [NSString stringWithFormat:@"%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", WX_BASE_URL, WX_AppID, refreshToken];
            [manager GET:refreshUrlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"请求reAccess的response = %@", responseObject);
                NSDictionary *refreshDict = [NSDictionary dictionaryWithDictionary:responseObject];
                NSString *reAccessToken = [refreshDict objectForKey:WX_ACCESS_TOKEN];
                // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
                if (reAccessToken) {
                    // 更新access_token、refresh_token、open_id
                    UserDefaultsSave(reAccessToken, WX_ACCESS_TOKEN);
                    UserDefaultsSave([refreshDict objectForKey:WX_OPEN_ID], WX_OPEN_ID);
                    UserDefaultsSave([refreshDict objectForKey:WX_REFRESH_TOKEN], WX_REFRESH_TOKEN);
                    [self getAccessToken:refreshDict[WX_ACCESS_TOKEN] OpenId:refreshDict[WX_OPEN_ID]];
                } else {
                    [self weChatLogin];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"用refresh_token来更新accessToken时出错 = %@", error);
                [super showHudWithText:error.localizedDescription];
                [super hideHudAfterSeconds:1.0];
            }];
            
        } else {
            [self weChatLogin];
        }
    }else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:actionConfirm];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)weChatLogin {
    [super showHudWithText:@"正在登录"];
    BOOL isSuccess = [WXApiRequestHandler sendAuthRequestScope:kAuthScope
                                                         State:kAuthState
                                                        OpenID:kAuthOpenID
                                              InViewController:self];
    if (!isSuccess) {
        [super hideHudAfterSeconds:1.0];
    }
}
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
    if (response.errCode == 0) {
        /*
         errCode
         ERR_OK = 0(用户同意)
         ERR_AUTH_DENIED = -4（用户拒绝授权）
         ERR_USER_CANCEL = -2（用户取消）
         */
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", @"text/plain", nil];
        NSString *accessUrlStr = [NSString stringWithFormat:@"%@/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", WX_BASE_URL, WX_AppID, WX_AppSecret, response.code];
        [manager GET:accessUrlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@", responseObject);
            NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
            if([accessDict.allKeys containsObject:@"errcode"] ||
               [accessDict.allKeys containsObject:@"errmsg"]) {
                [super showHudWithText:@"登录微信失败"];
            } else {
                UserDefaultsSave([accessDict objectForKey:WX_ACCESS_TOKEN], WX_ACCESS_TOKEN);
                UserDefaultsSave([accessDict objectForKey:WX_OPEN_ID], WX_OPEN_ID);
                UserDefaultsSave([accessDict objectForKey:WX_REFRESH_TOKEN], WX_REFRESH_TOKEN);
                [super showHudWithText:@"登录微信成功"];
                [self getAccessToken:accessDict[WX_ACCESS_TOKEN] OpenId:accessDict[WX_OPEN_ID]];
            }
            [super hideHudAfterSeconds:1.0];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"accessToken时出错 = %@", error);
            [super showHudWithText:error.localizedDescription];
            [super hideHudAfterSeconds:1.0];
            
        }];
    } else {
        NSLog(@"获取授权失败");
    }
}

//MARK: --微信刷新token
- (void)getAccessToken:(NSString *)access_Token OpenId:(NSString *)openId  {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", @"text/plain", nil];
    NSString *accessUrlStr = [NSString stringWithFormat:@"%@/userinfo?access_token=%@&openid=%@", WX_BASE_URL, access_Token, openId];
    [manager GET:accessUrlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"getAccessToken:%@", responseObject);
        [self loginApiWith:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        [super showHudWithText:error.localizedDescription];
        [super hideHudAfterSeconds:1.0];
    }];
}

- (void)loginApiWith:(id)paraDic {
    LoginApi *api = [[LoginApi alloc] initWithPara:paraDic];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"LoginApi:%@", request.responseObject);
        NSData *data = [request.responseObject[@"response"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([dic[CODE] intValue] == 200) {
            [super showHudWithText:@"登录成功"];
            [super hideHudAfterSeconds:1.0];
            
            JFUser *user = [JFUser mainJFUser];
            [user initWithJFUser:dic[DATA][@"userInfo"]];
            
            if (![Common isEmptyString:jfClientID]) {
                [self uploadClientID];
            }
            
            MMDrawerController *drawerVC = [kAppDelegate createHomeVC];
            kAppDelegate.window.rootViewController = drawerVC;
        } else {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
        }
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.error);
        [super showHudWithText:request.error.localizedDescription];
        [super hideHudAfterSeconds:1.0];
    }];
}

//MARK: AccessToken 是否有效
// https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID

// MARK: - 上传client id
- (void)uploadClientID {
    UserClientIdApi *api = [[UserClientIdApi alloc] init];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"UserClientId:%@", request.responseObject);
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"UserClientId:%@", request.error.localizedDescription);
    }];
    
}


@end
